package com.meitianhui.convenitenbuy.main.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.contract.SplashContract;
import com.meitianhui.convenitenbuy.main.di.DaggerMainComponent;
import com.meitianhui.convenitenbuy.main.di.MainModule;
import com.meitianhui.convenitenbuy.main.model.bean.AppToken;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.main.presenter.SplashPresenter;
import com.meitianhui.convenitenbuy.push.PushUtils;
import com.meitianhui.convenitenbuy.util.PreferenceUtils;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Action1;

/**
 * Created by Administrator on 2017/10/31.
 */

public class SplashActivity extends BaseActivity implements SplashContract.View {
    @Inject
    SplashPresenter presenter;
    private RxPermissions rxPermissions ;
    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_splash);
        DaggerMainComponent.builder()
                .appComponent(App.getInstance().getAppComponent())
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
        rxPermissions =  new RxPermissions(this);
        checkPermission();
    }


    private void checkPermission() {



//        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            if (!Settings.System.canWrite(this)) {
//                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
//                intent.setData(Uri.parse("package:" + this.getPackageName()));
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivityForResult(intent,0);
//            } else {
//
//            }
//        }
        setRxPermissions();


    }


    private  void setRxPermissions(){
        //有了权限，具体的动作
        rxPermissions
                .requestEach(Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.WRITE_SETTINGS,
                        Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION)
                .subscribe(permission -> {
                    if (permission.granted ) {
                        Observable.timer(2000, TimeUnit.MILLISECONDS)
                                .compose(RxUtils.rxSchedulerHelper()).subscribe(new Action1<Long>() {
                            @Override
                            public void call(Long aLong) {
                                intent();
                            }
                        });
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        TipUtils.showToast(App.getInstance(), "无权限");
                        finish();
                    }
                });
    }


    private void intent() {
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(Constants.PACKAGE_NAME, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if(info==null){
            TipUtils.showToast(App.getInstance(),"启动异常，请重新进入");
            finish();
        }else{
            int currentVersion = info.versionCode;
            int lastVersion = PreferenceUtils.getInt(SplashActivity.this, Constants.VERSION_CODE_KEY, 0);
            if (currentVersion > lastVersion) { //判断是否第一次启动
                PreferenceUtils.clear(SplashActivity.this);
                PreferenceUtils.putInt(SplashActivity.this, Constants.VERSION_CODE_KEY, currentVersion);
                Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                finish();
            } else {
                if (TextUtils.isEmpty(InfoProvider.getAppToken(SplashActivity.this))) {
                    presenter.getAppToken();
                } else {
                    //当用户信息有的时候
                    UserToken userToken = InfoProvider.getUserToken(SplashActivity.this);
                    if (userToken != null && InfoProvider.getLoginStatus(SplashActivity.this)) {
                        presenter.isReLoginHyphenate();
                    }
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));  //跳转到主界面
                    finish();
                }
            }
        }
    }


    @Override
    public void getTokenSuccess(AppToken appToken) {
        PreferenceUtils.putString(this, Constants.APP_TOKEN_KEY, appToken.getApp_token());
        PreferenceUtils.putString(this, Constants.APP_SECURITY_CODE, appToken.getSecurity_code());
        startActivity(new Intent(SplashActivity.this, MainActivity.class));  //跳转到主界面
        finish();
    }

    @Override
    public void getTokenFail(int code, String msg) {
        TipUtils.showToast(App.getInstance(), msg);
        this.finish();

    }

    /**
     *
     */
    @Override
    public void isReLoginHyphenateSuccess() {
        if (InfoProvider.getHyphenateInfo(this) != null) {
            presenter.loginHyphenate();
        }
    }

    @Override
    public void isReLoginHyphenateFail() {
        PushUtils.setAlias(this, "", null);
        PushUtils.setTags(this, null, null);
    }


    @Override
    public void showError(String msg) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == 0){
            //有了权限，具体的动作
            setRxPermissions();
        }else{
            TipUtils.showToast(App.getInstance(),"为了提升用户体验，请允许此项权限");
        }


    }
}
